/* eslint-disable array-callback-return */
'use strict';

const Controller = require('../core/base_controller');
const fs = require('fs');
const xlsx = require('xlsx');
const Excel = require('exceljs');

function toInt(str) {
  if (typeof str === 'number') return str;
  if (!str) return str;
  return parseInt(str, 10) || 0;
}

const nametokey = {
    店铺名: 'store_name',
    姓名: 'user_name',
    电话: 'telephone',
    地址: 'address',
    型号: 'model',
    数量: 'num',
    报单日期: 'date',
    备注: 'remark',
  },
  exp = {
    姓名: 'user_name',
    电话: 'telephone',
    地址: 'address',
    型号: 'model',
    数量: 'num',
    备注: 'remark',
  };

class StoreController extends Controller {
  async storebulkCreate() {
    const ctx = this.ctx;
    const file = ctx.request.files[0]; // 假设上传的文件在 request 的 files 数组中的第一个位置
    const workbook = xlsx.readFile(file.filepath);
    const worksheet = workbook.Sheets[workbook.SheetNames[0]];
    const jsonData = xlsx.utils.sheet_to_json(worksheet);
    const res = jsonData?.map(it => {
      const newit = {};
      Object.keys(it)?.map(its => {
        if (its === '报单日期') {
          const dateValue =
            isNaN(it[its]) || parseInt(it[its]) < 10000
              ? null
              : parseInt(it[its]);
          const date = dateValue
            ? new Date((dateValue - (25567 + 2)) * 86400 * 1000)
            : new Date();
          newit[nametokey[its]] = date;
          return;
        }
        newit[nametokey[its]] = it[its];
      });
      return newit;
    });

    try {
      const result = await ctx.model.Store.bulkCreate(res);
      this.success(result);
    } catch (err) {
      const result = '数据导入失败：' + err.message;
      this.fail(result);
    } finally {
      // 删除临时文件
      fs.unlinkSync(file.filepath);
    }
  }

  async storeexport() {
    const ctx = this.ctx;
    const { Op } = this.app.Sequelize;
    const {
      store_name,
      user_name,
      telephone,
      address,
      model,
      date,
      remark,
      ids,
    } = ctx.query;
    const where = {};
    if (store_name) {
      where.store_name = {
        [Op.like]: `%${store_name}%`,
      };
    }
    if (user_name) {
      where.user_name = {
        [Op.like]: `%${user_name}%`,
      };
    }
    if (telephone) {
      where.telephone = {
        [Op.like]: `%${telephone}%`,
      };
    }
    if (address) {
      where.address = {
        [Op.like]: `%${address}%`,
      };
    }
    if (model) {
      where.model = {
        [Op.like]: `%${model}%`,
      };
    }
    if (date) {
      where.date = {
        [Op.between]: date.split(',')?.map(it => {
          return new Date(it);
        }),
      };
    }
    if (remark) {
      where.remark = {
        [Op.like]: `%${remark}%`,
      };
    }
    if (ids) {
      where.id = ids.split(',');
    }

    const result = await ctx.model.Store.findAndCountAll({
      where,
      order: [[ 'created_at', 'DESC' ]],
    });

    const workbook = new Excel.Workbook(); // 创建工作簿
    const worksheet = workbook.addWorksheet('Sheet'); // 创建工作表
    const columns = Object.keys(exp)?.map(it => {
      return {
        header: it,
        key: exp[it],
        width: [ 'address', 'remark' ].includes(exp[it]) ? 66 : 20,
      };
    });
    worksheet.columns = columns;
    result?.rows?.map(item => {
      const vals = item.dataValues;
      const valarr = Object.values(exp)?.map(it => {
        return vals[it];
      });
      worksheet.addRow(valarr);
    });

    const buffer = await workbook.xlsx.writeBuffer();
    // 设置响应头
    ctx.set(
      'Content-Type',
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    );
    ctx.set('Content-Disposition', 'attachment; filename=myfile.xlsx');
    ctx.set('responseType', 'arraybuffer');
    // 将 Buffer 返回给客户端进行下载
    ctx.body = buffer;
  }

  async index() {
    const ctx = this.ctx;
    const { Op } = this.app.Sequelize;
    const {
      pageIndex,
      pageSize,
      store_name,
      user_name,
      telephone,
      address,
      model,
      date,
      remark,
    } = ctx.query;
    const page = pageIndex,
      limit = pageSize,
      where = {};

    if (store_name) {
      where.store_name = {
        [Op.like]: `%${store_name}%`,
      };
    }
    if (user_name) {
      where.user_name = {
        [Op.like]: `%${user_name}%`,
      };
    }
    if (telephone) {
      where.telephone = {
        [Op.like]: `%${telephone}%`,
      };
    }
    if (address) {
      where.address = {
        [Op.like]: `%${address}%`,
      };
    }
    if (model) {
      where.model = {
        [Op.like]: `%${model}%`,
      };
    }

    if (date) {
      where.date = {
        [Op.between]: date.split(',')?.map(it => {
          return new Date(it);
        }),
      };
    }
    if (remark) {
      where.remark = {
        [Op.like]: `%${remark}%`,
      };
    }
    const result = await ctx.model.Store.findAndCountAll({
      order: [[ 'created_at', 'DESC' ]],
      offset: (page - 1) * limit,
      limit: parseInt(limit),
      where,
    });

    this.success(result);
  }

  async show() {
    const ctx = this.ctx;
    const result = await ctx.model.Store.findByPk(toInt(ctx.params.id));
    this.success(result);
  }

  async create() {
    const ctx = this.ctx;
    if (
      !ctx.request.body.user_name ||
      !ctx.request.body.telephone ||
      !ctx.request.body.date
    ) {
      this.fail('请完善必填项！');
      return;
    }
    const store = await ctx.model.Store.create(ctx.request.body);
    await ctx.service.user.update(
      {
        role_type: ctx.request.body?.store_join_key,
        store_id: store.id,
      },
      this
    );
    this.success(store);
  }

  async update() {
    const ctx = this.ctx;
    const id = toInt(ctx.params.id);
    const store = await ctx.model.Store.findByPk(id);
    if (!store) {
      ctx.status = 404;
      ctx.body = {
        code: 1,
        success: false,
        msg: '库里没有该条数据',
      };
      return;
    }
    await store.update(ctx.request.body);
    this.success(store);
  }

  async mutipledestroy() {
    const ctx = this.ctx;
    const { ids } = ctx.request.body;
    // 执行数据库操作来删除用户
    const store = await ctx.model.Store.destroy({
      where: {
        id: ids, // 根据ID进行匹配删除
      },
    });

    if (!store) {
      this.fail('删除失败！请重试！');
      return;
    }

    this.success({
      data: '已删除',
    });
  }

  async destroy() {
    const ctx = this.ctx;
    const id = toInt(ctx.params.id);
    const store = await ctx.model.Store.findByPk(id);
    if (!store) {
      ctx.status = 404;
      ctx.body = {
        code: 1,
        success: false,
        msg: '库里没有该条数据',
      };
      return;
    }

    await store.destroy();
    this.success({
      data: '已删除',
    });
  }
}

module.exports = StoreController;
